package com.fine.demo.keyboard

import android.content.Context
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.util.AttributeSet
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.EditText

class IEditText : EditText, KeyboardView.OnKeyboardActionListener{

    private lateinit var mContext: Context
    private lateinit var keyboardNumber: Keyboard
    private lateinit var keyboardEnglish: Keyboard
    private var mViewGroup: ViewGroup? = null
    private var mKeyboardView: MKeyboardView? = null

    private var isNumber = true  //数字键盘和英文键盘之间的切换
    private var isCapitalEnglish = false  //英文键盘是否为大写

    private var onKeyboardListener: OnKeyboardListener? = null

    constructor(context: Context): super(context) {
        initEditText(context)
    }

    constructor(context: Context, attrs: AttributeSet?): super(context, attrs) {
        initEditText(context)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr){
        initEditText(context)
    }

    private fun initEditText(context: Context) {
        this.mContext = context
        keyboardNumber = Keyboard(mContext, R.xml.keyboard_number)
        keyboardEnglish = Keyboard(mContext, R.xml.keyboard_english)
    }

    interface OnKeyboardListener {
        fun onHide(isCompleted: Boolean)
        fun onShow()
        fun onPress(primaryCode: Int)
    }

    fun setOnKeyboardListener(onKeyboardListener: OnKeyboardListener) {
        this.onKeyboardListener = onKeyboardListener
    }

    fun setEditView(viewGroup: ViewGroup, keyboardView: MKeyboardView, isNumber: Boolean) {
        this.mViewGroup = viewGroup
        this.mKeyboardView = keyboardView
        this.isNumber = isNumber

        changeKeyboard(isNumber)
        keyboardView.setOnKeyboardActionListener(this)

    }

    private fun changeKeyboard(isNumber: Boolean) {
        if(isNumber) {
            this.mKeyboardView?.keyboard = keyboardNumber
            this.mKeyboardView?.setCurrentKeyboard(0)
        } else {
            this.mKeyboardView?.keyboard = keyboardEnglish
            this.mKeyboardView?.setCurrentKeyboard(1)
        }

        this.mKeyboardView?.isEnabled = true
        this.mKeyboardView?.isPreviewEnabled = !isNumber
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        SystemUtil.showKeyboard(mContext)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        SystemUtil.closeKeyboard(this)
        this.mKeyboardView = null
        this.mViewGroup = null
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        super.onTouchEvent(event)
        requestFocus()
        requestFocusFromTouch()
        if(event?.action == MotionEvent.ACTION_UP) {
            if(!isShow()) {
                show()
            }
        }
        SystemUtil.closeKeyboard(this)
        return true
    }

    public fun show(){
        mKeyboardView?.let {
            if(it.visibility == View.INVISIBLE || it.visibility == View.GONE) {
                it.visibility = View.VISIBLE
                if(mViewGroup != null) {
                    mViewGroup!!.visibility = View.VISIBLE
                }
            }
            onKeyboardListener?.onShow()
        }
    }

    public fun hide(isCompleted: Boolean) {
        mKeyboardView?.let {
            if(it.visibility == View.VISIBLE) {
                it.visibility = View.INVISIBLE
                if(mViewGroup != null) {
                    mViewGroup!!.visibility = View.GONE
                }
            }
            onKeyboardListener?.onHide(isCompleted)
        }
    }

    public fun isShow(): Boolean {
        return mKeyboardView?.visibility == View.VISIBLE
    }

    override fun swipeRight() {
        Log.i("Fine", "swipeRight---->")
    }

    override fun onPress(primaryCode: Int) {
        onKeyboardListener?.onPress(primaryCode)
        setPreview(primaryCode)
    }

    private fun setPreview(primaryCode: Int) {
        val list = listOf(Keyboard.KEYCODE_DONE, -11, 32, -5, -6, -3, -1)
        mKeyboardView?.isPreviewEnabled = !list.contains(primaryCode)
    }

    override fun onRelease(primaryCode: Int) {

    }

    override fun swipeLeft() {
        Log.i("Fine", "swipeLeft---->")
    }

    override fun swipeUp() {
    }

    override fun swipeDown() {
    }

    override fun onKey(primaryCode: Int, keyCodes: IntArray?) {
        val editable = text
        val start = selectionStart
        when(primaryCode) {
            -6 ->{
                changeKeyboard(true)
            }   //切换数字键盘
            Keyboard.KEYCODE_DELETE -> {
                if(editable != null && editable.isNotEmpty() && start > 0) {
                    editable.delete(start -1, start)
                }
            }       //删除键
            Keyboard.KEYCODE_DONE -> {
                hide(true)
            }     //确定
            -11 ->{
                changeKeyboard(false)
            }    //返回，只有数字键盘才有返回，返回到英文键盘
            -1 ->{
                shiftEnglish()
            }   //大小写
            -3 -> {

            }   //符号
            else -> {
                editable.insert(start, "${primaryCode.toChar()}")
            }

        }
    }

    //大小写切换
    private fun shiftEnglish() {
        val keyList = keyboardEnglish.keys
        for (key in keyList) {
            if(null != key.label && isKey(key.label.toString())) {
                if(isCapitalEnglish) {
                    key.label = key.label.toString().toLowerCase()
                    key.codes[0] = key.codes[0] + 32
                } else {
                    key.label = key.label.toString().toUpperCase()
                    key.codes[0] = key.codes[0] - 32
                }
            }
        }
        isCapitalEnglish = !isCapitalEnglish
    }

    private fun isKey(keyLabel: String): Boolean {
        val lowercase = "abcdefghijklmnopqrstuvwxyz"
        if(lowercase.indexOf(keyLabel.toLowerCase()) > -1) {
            return true
        }
        return false
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            hide(false)
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onText(text: CharSequence?) {
    }

}